package com.settlement.system.service.impl;

import com.lmax.disruptor.RingBuffer;
import com.settlement.system.handler.disruptor.MessageVo;
import com.settlement.system.service.DisruptorMqService;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class DisruptorMqServiceImpl implements DisruptorMqService {
    Logger log = LoggerFactory.getLogger(DisruptorMqServiceImpl.class);

    private final RingBuffer<MessageVo> messageVoRingBuffer;

    @Override
    public void handle(MessageVo vo) {
        log.info("打印事件参数: {}", vo);
        //获取下一个Event槽的下标
        long sequence = messageVoRingBuffer.next();
        try {
            //给Event填充数据
            MessageVo event = messageVoRingBuffer.get(sequence);
            BeanUtils.copyProperties(vo, event);
            log.info("往消息队列中添加消息：{}", event);
        } catch (Exception e) {
            log.error("添加事件失败 MessageVoRingBuffer for : e = {},{}", e, e.getMessage());
        } finally {
            //发布Event，激活观察者去消费，将sequence传递给改消费者
            //注意最后的publish方法必须放在finally中以确保必须得到调用；如果某个请求的sequence未被提交将会堵塞后续的发布操作或者其他的producer
            messageVoRingBuffer.publish(sequence);
        }
    }


}
